import axios from "./index";
import { encrypt } from "../utils/crypto";

/**
 * API接口集合
 * 包含用户认证、课程管理、组织管理等功能
 */
export default {
  /**
   * 验证用户身份
   * @returns {Promise<Object>} 返回验证结果，状态码200表示成功，401表示未授权
   */
  verifyUser: async () => {
    return { status: 200 };
    try {
      const username = localStorage.getItem("userId");
      const token = localStorage.getItem("token");
      return await axios.post("/api/users/verify_user", null, {
        params: {
          username: username,
          token: token
        }
      });
    } catch (error) {
      console.error("验证用户异常", error);
      // throw error
      return { status: 401 };
    }
  },

  /**
   * 用户登录
   * @param {string} studentId - 学号
   * @param {string} websitePw - 网站密码
   * @returns {Promise<Object>} 返回登录结果
   */
  userLogin: async (studentId: any, websitePw: any) => {
    try {
      return await axios.post("/api/users/login/", null, {
        params: { student_id: studentId, website_pw: websitePw }
      });
    } catch (error) {
      console.error("登录异常", error);
      throw error;
    }
  },

  /**
   * 用户注册
   * @param {string} studentId - 学号
   * @param {string} websitePw - 网站密码
   * @param {string} email - 电子邮箱
   * @returns {Promise<Object>} 返回注册结果
   */
  userRegister: async (studentId: any, websitePw: any, email: any) => {
    try {
      return await axios.post("/api/users/register/", {
        username: studentId,
        password: websitePw,
        email: email
      });
    } catch (error) {
      console.error("注册异常", error);
      throw error;
    }
  },

  /**
   * 获取课表
   * @param {string} studentId - 学号
   * @param {string} password - 密码（加密后）
   * @param {string} selectedYear - 学年
   * @param {string} selectedTerm - 学期
   * @param {boolean} hardUpdate - 是否强制更新
   * @returns {Promise<Object>} 返回课表数据
   */
  getSchedule: async (studentId: any, password: any, selectedYear: any, selectedTerm: any, hardUpdate: any) => {
    try {
      return await axios.get("/api/sched/get_sched", {
        params: {
          student_id: studentId,
          student_pw: encrypt(password),
          year: selectedYear,
          semester: selectedTerm,
          hard_update: hardUpdate
        }
      });
    } catch (error) {
      console.error("获取课表异常", error);
      throw error;
    }
  },

  /**
   * 获取全部课表
   * @returns {Promise<Object>} 返回全部课表数据
   */
  getAllSchedules: async () => {
    try {
      return await axios.get("/api/sched/get_all_sched", {
        params: {
          user_id: localStorage.getItem("userId"),
          token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("获取全部课表异常", error);
      throw error;
    }
  },

  /**
   * 获取全部课程
   * @returns {Promise<Object>} 返回所有课程数据
   */
  getAllCourse: async () => {
    try {
      return await axios.get("/api/course/get_course", { timeout: 600000 }); // 设置超时时间为10分钟
    } catch (error) {
      console.error("获取全部课程异常", error);
      throw error;
    }
  },

  /**
   * 修改密码
   * @param {string} studentId - 学号
   * @param {string} oldPassword - 旧密码
   * @param {string} newPassword - 新密码
   * @returns {Promise<Object>} 返回修改结果
   */
  changePassword: async (studentId: any, oldPassword: any, newPassword: any) => {
    try {
      return await axios.post("/api/users/change_password/", null, {
        params: { username: studentId, old_password: oldPassword, new_password: newPassword }
      });
    } catch (error) {
      console.error("修改密码异常", error);
      throw error;
    }
  },

  /**
   * 获取用户信息
   * @param {string} username - 用户名
   * @param {string} token - 访问令牌
   * @returns {Promise<Object>} 返回用户信息
   */
  getUserInfo: async (username: any, token: any) => {
    try {
      return await axios.get("/api/users/get_all_users/", {
        params: {
          admin_username: username,
          token: token
        }
      });
    } catch (error: any) {
      if (error.response) {
        // 服务器响应了，但状态码不在 2xx 范围内
        console.error("获取用户信息异常", error.response.data);
        console.error("状态码", error.response.status);
        console.error("响应头", error.response.headers);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        console.error("没有收到响应", error.request);
      } else {
        // 其他错误
        console.error("错误", error.message);
      }
      throw error;
    }
  },

  /**
   * 强制设置用户密码
   * @param {string} username - 用户名
   * @param {string} new_password - 新密码
   * @param {string} admin_username - 管理员用户名
   * @param {string} token - 访问令牌
   * @returns {Promise<Object>} 返回操作结果
   */
  forceUser: async (username: any, new_password: any, admin_username: any, token: any) => {
    try {
      return await axios.post("/api/users/force_set_password/", null, {
        params: {
          username: username,
          new_password: new_password,
          admin_username: admin_username,
          token: token
        }
      });
    } catch (error) {
      console.error("强制重置密码异常", error);
      throw error;
    }
  },

  /**
   * 设置用户状态
   * @param {string} admin_username - 管理员用户名
   * @param {string} token - 访问令牌
   * @param {string} username - 用户名
   * @param {string} new_status - 新状态
   * @returns {Promise<Object>} 返回操作结果
   */
  userStatus: async (admin_username: any, token: any, username: any, new_status: any) => {
    try {
      return await axios.post("/api/users/set_user_status/", null, {
        params: {
          admin_username: admin_username,
          token: token,
          username: username,
          new_status: new_status
        }
      });
    } catch (error) {
      console.error("修改用户状态异常", error);
      throw error;
    }
  },

  /**
   * 更新用户角色
   * @param {string} admin_username - 管理员用户名
   * @param {string} token - 访问令牌
   * @param {string} username - 用户名
   * @param {string} new_role - 新角色
   * @returns {Promise<Object>} 返回操作结果
   */
  updateUserRole: async (admin_username: any, token: any, username: any, new_role: any) => {
    try {
      return await axios.post("/api/users/set_user_role/", null, {
        params: {
          admin_username: admin_username,
          token: token,
          username: username,
          new_role: new_role
        }
      });
    } catch (error) {
      console.error("修改用户角色异常", error);
      throw error;
    }
  },

  /**
   * 创建组织
   * @param {string} user_id - 用户ID
   * @param {string} organizationName - 组织名称
   * @param {string} organizationDescription - 组织描述
   * @param {string} organizationYear - 组织学年
   * @param {string} organizationTerm - 组织学期
   * @returns {Promise<Object>} 返回创建结果
   */
  addOrganization: async (
    // 创建组织
    user_id: any,
    organizationName: any,
    organizationDescription: any,
    organizationYear: any,
    organizationTerm: any
  ) => {
    try {
      return await axios.post("/api/org/create_org", null, {
        params: {
          user_id: user_id,
          org_name: organizationName,
          org_description: organizationDescription,
          course_year: organizationYear.toString(),
          course_term: organizationTerm.toString()
        }
      });
    } catch (error) {
      console.error("新增组织异常", error);
      throw error;
    }
  },

  /**
   * 获取组织列表
   * @param {string} user_id - 用户ID
   * @returns {Promise<Object>} 返回组织列表
   */
  getOrganizationList: async (user_id: any) => {
    // 获取组织列表
    try {
      return await axios.get("/api/org/get_my_org", { params: { user_id: user_id } });
    } catch (error) {
      console.error("获取组织列表异常", error);
      throw error;
    }
  },

  /**
   * 获取消息列表
   * @param {string} user_id - 用户ID
   * @returns {Promise<Object>} 返回消息列表
   */
  getMsgList: async (user_id: any) => {
    // 获取有关我的全部消息列表
    try {
      return await axios.get("/api/org/get_org_all_msg", { params: { user_id: user_id } });
    } catch (error) {
      console.error("获取消息列表异常", error);
      throw error;
    }
  },

  /**
   * 搜索组织
   * @param {string} org_id - 组织ID，多个ID用逗号分隔
   * @returns {Promise<Object>} 返回搜索结果
   */
  searchOrg: async (org_id: any) => {
    // 搜索组织
    try {
      // 将 org_id 拆分为数组
      const orgIdsArray = org_id.split(",");

      // 使用重复参数名的格式（org_ids=1&org_ids=2）
      const params = new URLSearchParams();
      orgIdsArray.forEach((id: any) => {
        params.append("org_ids", id);
      });
      return await axios.get("/api/org/search_org", { params: params });
    } catch (error) {
      console.error("搜索组织异常", error);
      throw error;
    }
  },

  /**
   * 搜索组织成员
   * @param {string} user_name - 用户名，多个用户名用逗号分隔
   * @returns {Promise<Object>} 返回搜索结果
   */
  seachMember: async (user_name: any) => {
    // 搜索组织成员
    try {
      const userNamesArray = user_name.split(",");
      const params = new URLSearchParams();
      userNamesArray.forEach((name: any) => {
        params.append("user_names", name);
      });
      return await axios.get("/api/org/search_member", { params: params });
    } catch (error) {
      console.error("搜索组织成员异常", error);
      throw error;
    }
  },

  /**
   * 删除组织成员
   * @param {string} user_id - 用户ID
   * @param {string} org_id - 组织ID
   * @returns {Promise<Object>} 返回操作结果
   */
  deleteMember: async (user_id: any, org_id: any) => {
    // 删除组织成员
    try {
      const token = localStorage.getItem("token");
      return await axios.post("/api/org/delete_org_member", null, {
        params: { user_id: user_id, org_id: org_id, token: token }
      });
    } catch (error) {
      console.error("删除组织成员异常", error);
      throw error;
    }
  },

  /**
   * 申请加入组织
   * @param {string} user_id - 用户ID
   * @param {Array<string>} org_ids - 组织ID数组
   * @returns {Promise<Object>} 返回申请结果
   */
  requestJoinOrg: async (user_id: any, org_ids: any) => {
    // 申请加入组织
    try {
      // const org_ids = org_id.split(',')
      const params = new URLSearchParams();
      params.append("user_id", user_id);
      org_ids.forEach((id: any) => {
        params.append("org_ids", id);
      });
      return await axios.post("/api/org/apply_org", null, { params: params });
    } catch (error) {
      console.error("申请加入组织异常", error);
      throw error;
    }
  },

  /**
   * 邀请成员
   * @param {Array<string>} org_ids - 组织ID数组
   * @param {string} inviter_id - 邀请人ID
   * @param {Array<string>} invitee_ids - 被邀请人ID数组
   * @returns {Promise<Object>} 返回邀请结果
   */
  inviteMember: async (org_ids: any, inviter_id: any, invitee_ids: any) => {
    // 邀请成员
    try {
      // const org_ids = org_id.split(',')
      // const invitee_ids = invitee_id.split(',')
      const params = new URLSearchParams();
      org_ids.forEach((id: any) => {
        params.append("org_ids", id);
      });
      invitee_ids.forEach((id: any) => {
        params.append("invitee_ids", id);
      });
      params.append("inviter_id", inviter_id);
      return await axios.post("/api/org/invite_org", null, { params: params });
    } catch (error) {
      console.error("邀请成员异常", error);
      throw error;
    }
  },

  /**
   * 设置邀请状态
   * @param {Array<string>} invitation_ids - 邀请ID数组
   * @param {string} status - 新状态
   * @returns {Promise<Object>} 返回操作结果
   */
  setInvitationStatus: async (invitation_ids: any, status: any) => {
    // 设置邀请状态
    try {
      const params = new URLSearchParams();
      invitation_ids.forEach((id: any) => {
        params.append("invitation_ids", id);
      });
      params.append("status", status);
      return await axios.post("/api/org/set_org_invitation_status", null, {
        params: params
      });
    } catch (error) {
      console.error("设置邀请状态异常", error);
      throw error;
    }
  },

  /**
   * 设置申请状态
   * @param {Array<string>} request_ids - 申请ID数组
   * @param {string} status - 新状态
   * @returns {Promise<Object>} 返回操作结果
   */
  setRequestStatus: async (request_ids: any, status: any) => {
    // 设置申请状态
    try {
      const params = new URLSearchParams();
      request_ids.forEach((id: any) => {
        params.append("request_ids", id);
      });
      params.append("status", status);
      return await axios.post("/api/org/set_org_request_status", null, { params: params });
    } catch (error) {
      console.error("设置申请状态异常", error);
      throw error;
    }
  },

  /**
   * 撤回消息
   * @param {Array<string>} msg_ids - 消息ID数组
   * @param {string} type - 消息类型
   * @returns {Promise<Object>} 返回操作结果
   */
  withdrawMsg: async (msg_ids: any, type: any) => {
    // 撤回消息
    try {
      const params = new URLSearchParams();
      msg_ids.forEach((id: any) => {
        params.append("msg_ids", id);
      });
      params.append("type", type);
      return await axios.post("/api/org/withdraw_org_request", null, {
        params: params
      });
    } catch (error) {
      console.error("撤回消息异常", error);
      throw error;
    }
  },

  /**
   * 获取组织无课课表
   * @param {string} org_id - 组织ID
   * @returns {Promise<Object>} 返回无课课表数据
   */
  getOrgNoClassSchedules: async (org_id: any) => {
    // 获取组织无课课表
    try {
      return await axios.get("/api/org/get_org_no_class_schedule", {
        params: { org_id: org_id, start_week: 1, end_week: 19 }
      });
    } catch (error) {
      console.error("获取组织无课课表异常", error);
      throw error;
    }
  },

  /**
   * 获取组织成员
   * @param {string} org_id - 组织ID
   * @returns {Promise<Object>} 返回组织成员列表
   */
  getOrgMembers: async (org_id: any) => {
    // 获取组织成员
    try {
      return await axios.get("/api/org/get_org_members", { params: { org_id: org_id } });
    } catch (error) {
      console.error("获取组织成员异常", error);
      throw error;
    }
  },

  /**
   * 获取组织排班表
   * @param {string} org_id - 组织ID
   * @param {number} start_week - 开始周
   * @param {number} end_week - 结束周
   * @param {Array<string>} valid_times - 有效时间段
   * @param {Array<string>} exclude_name - 排除的成员名称
   * @param {Object} config - 配置参数
   * @returns {Promise<Object>} 返回排班表数据
   */
  getOrgDutyTable: async (
    org_id: any,
    start_week: any,
    end_week: any,
    valid_times: any,
    exclude_name: any,
    config: any
  ) => {
    // 获取组织排班表
    try {
      const params = new URLSearchParams();
      params.append("org_id", org_id);
      params.append("start_week", start_week);
      params.append("end_week", end_week);
      valid_times.forEach((time: any) => {
        params.append("valid_times", time);
      });
      exclude_name.forEach((name: any) => {
        params.append("exclude_name", name);
      });
      params.append("config", JSON.stringify(config));
      return await axios.get("/api/org/get_org_duty_table", {
        params: params
      });
    } catch (error) {
      console.error("获取组织排班表异常", error);
      throw error;
    }
  },

  /**
   * 获取个人课程数据
   * @param {string} user_id - 用户ID
   * @param {string} student_id - 学号
   * @param {string} student_pw - 学生密码（加密后）
   * @param {boolean} hardUpdate - 是否强制更新
   * @returns {Promise<Object>} 返回个人课程数据
   */
  getPersonalCourseData: async (user_id: any, student_id: any, student_pw: any, hardUpdate: any) => {
    try {
      const response = await axios.get("/api/sched/get_student_course", {
        params: {
          user_id: user_id,
          student_id: student_id,
          student_pw: encrypt(student_pw),
          hard_update: hardUpdate
        },
        timeout: 60000 // 设置响应时长为1分钟
      });
      return response;
    } catch (error) {
      console.error("获取个人课表异常", error);
      throw error;
    }
  },

  /**
   * 获取AI选课关键词
   * @param {Array<string>} interests - 兴趣列表
   * @param {string} career_goal - 职业目标
   * @returns {Promise<Object>} 返回AI选课关键词
   */
  getAiSelectedWords: async (interests: string[], career_goal: string) => {
    try {
      const params = new URLSearchParams();
      interests.forEach((interest: any) => {
        params.append("interests", interest);
      });
      params.append("career_goal", career_goal);
      return await axios.get("/api/course/get_ai_select_worlds", {
        params: params,
        timeout: 60000 // 设置响应时长为1分钟
      });
    } catch (error) {
      console.error("获取AI选课词异常", error);
      throw error;
    }
  },

  /**
   * 获取AI选课推荐
   * @param {Array<string>} interests - 兴趣列表
   * @param {string} career_goal - 职业目标
   * @param {string} user_id - 用户ID
   * @param {Array<string>} select_worlds - 选课关键词
   * @returns {Promise<Object>} 返回AI选课推荐
   */
  getAiSelectedCourses: async (interests: string[], career_goal: string, user_id: string, select_worlds: string[]) => {
    try {
      const params = new URLSearchParams();
      interests.forEach((interest: any) => {
        params.append("interests", interest);
      });
      params.append("career_goal", career_goal);
      params.append("user_id", user_id);
      select_worlds.forEach((world: any) => {
        params.append("select_worlds", world);
      });
      return await axios.get("/api/course/get_ai_select_courses", {
        params: params,
        timeout: 600000 // 设置响应时长为10分钟
      });
    } catch (error) {
      console.error("获取AI选课异常", error);
      throw error;
    }
  },

  /**
   * 获取AI推荐历史
   * @param {string} user_id - 用户ID
   * @returns {Promise<Object>} 返回AI推荐历史
   */
  getAiRecommendHistory: async (user_id: string) => {
    try {
      return await axios.get("/api/course/get_course_recommend", {
        params: { user_id: user_id }
      });
    } catch (error) {
      console.error("获取AI推荐历史异常", error);
      throw error;
    }
  },

  /**
   * 获取映射状态
   * @returns {Promise<Object>} 返回映射状态
   */
  getSeigFrpStatus: async () => {
    try {
      return await axios.get("/api/course/get_seig_frp_status");
    } catch (error) {
      console.error("获取映射状态异常", error);
      throw error;
    }
  },

  /**
   * 获取今日问候语
   * @returns {Promise<Object>} 返回今日问候语
   */
  getTodayGreeting: async () => {
    try {
      const res = await axios.get("/api/users/get_today_sentence");
      return res;
    } catch (error) {
      console.error("获取今日诗词异常", error);
      throw error;
    }
  },

  /**
   * 上传反馈图片
   * @param {FormData} formData - 包含图片的表单数据
   * @returns {Promise<Object>} 返回上传结果
   */
  uploadFeedbackImage: async (formData: any) => {
    try {
      return await axios.post("/api/feedback/upload_image", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });
    } catch (error) {
      console.error("上传反馈图片异常", error);
      throw error;
    }
  },

  /**
   * 提交反馈
   * @param {Object} data - 反馈数据
   * @param {string} data.content - 反馈内容
   * @param {number} data.rating - 评分
   * @param {string} [data.contact] - 联系方式（可选）
   * @param {Array<string>} data.images - 图片列表
   * @returns {Promise<Object>} 返回提交结果
   */
  submitFeedback: async (data: { content: string; rating: number; contact?: string; images: string[] }) => {
    const formData = new FormData();
    formData.append("content", data.content);
    formData.append("rating", data.rating.toString());
    if (data.contact) formData.append("contact", data.contact);
    data.images.forEach((img: any) => formData.append("images", img));

    try {
      return await axios.post("/api/feedback/submit_feedback", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });
    } catch (error) {
      console.error("提交反馈异常", error);
      throw error;
    }
  },

  /**
   * 获取反馈
   * @returns {Promise<Object>} 返回反馈数据
   */
  getFeedback: async () => {
    try {
      return await axios.get("/api/feedback/get_feedback");
    } catch (error) {
      console.error("获取反馈异常", error);
      throw error;
    }
  },

  /**
   * 获取课程-教评数据
   * @param {string} course_code - 课程代码
   * @returns {Promise<Object>} 返回课程-教评数据
   */
  getCourseGradeTeacher: async (course_code: string) => {
    try {
      return await axios.get("/api/course/get_course_grade_teacher_map", {
        params: { course_code: course_code }
      });
    } catch (error) {
      console.error("获取课程-教评数据异常", error);
      throw error;
    }
  },

  /**
   * 重置密码
   * @param {string} username - 用户名
   * @returns {Promise<Object>} 返回重置结果
   */
  resetPassword: async (username: string) => {
    try {
      return await axios.post("/api/users/reset_password", null, {
        params: { username: username }
      });
    } catch (error) {
      console.error("重置密码异常", error);
      throw error;
    }
  },

  /**
   * 获取识别码
   * @returns {Promise<Object>} 返回识别码
   */
  getRecognitionCode: async () => {
    try {
      return await axios.get("/api/miniapp/get_recognition_code", {
        params: {
          user_id: localStorage.getItem("userId")
        }
      });
    } catch (error) {
      console.error("获取识别码异常", error);
      throw error;
    }
  },

  /**
   * 获取微信小程序码
   * @returns {Promise<Object>} 返回微信小程序码
   */
  getWxacode: async () => {
    try {
      return await axios.get("/api/miniapp/get_wxacode", {
        params: {
          scene: localStorage.getItem("userId")
        }
      });
    } catch (error) {
      console.error("获取微信小程序码异常", error);
      throw error;
    }
  },

  /**
   * 获取用户微信OpenID绑定状态
   * @returns {Promise<Object>} 返回绑定状态
   */
  getUserWxOpenidStatus: async () => {
    try {
      return await axios.get("/api/miniapp/get_user_wx_openid_status", {
        params: {
          user_id: localStorage.getItem("userId"),
          access_token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("获取用户识别码绑定状态异常", error);
      throw error;
    }
  },

  /**
   * 获取所有更新日志
   * @returns {Promise<Object>} 返回所有更新日志
   */
  getAllUpdateLogs: async () => {
    try {
      return await axios.get("/api/miniapp/update_logs");
    } catch (error) {
      console.error("获取更新日志列表异常", error);
      throw error;
    }
  },

  /**
   * 创建更新日志
   * @param {Object} logData - 日志数据
   * @returns {Promise<Object>} 返回创建结果
   */
  createUpdateLog: async (logData: { update_content: string }) => {
    try {
      return await axios.post("/api/miniapp/update_logs", logData.update_content, {
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.error("创建更新日志异常", error);
      throw error;
    }
  },

  /**
   * 更新日志
   * @param {number} logId - 日志ID
   * @param {Object} logData - 日志数据
   * @returns {Promise<Object>} 返回更新结果
   */
  updateUpdateLog: async (logId: number, logData: { update_content: string }) => {
    try {
      return await axios.put(`/api/miniapp/update_logs/${logId}`, logData.update_content, {
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.error("更新日志异常", error);
      throw error;
    }
  },

  /**
   * 删除日志
   * @param {number} logId - 日志ID
   * @returns {Promise<Object>} 返回删除结果
   */
  deleteUpdateLog: async (logId: number) => {
    try {
      return await axios.delete(`/api/miniapp/update_logs/${logId}`);
    } catch (error) {
      console.error("删除日志异常", error);
      throw error;
    }
  },

  /**
   * 获取使用文档
   * @returns {Promise<Object>} 返回使用文档
   */
  getUseDoc: async () => {
    try {
      return await axios.get("/api/miniapp/get_use_doc");
    } catch (error) {
      console.error("获取使用文档异常", error);
      throw error;
    }
  },

  /**
   * 获取最新使用文档
   * @returns {Promise<Object>} 返回最新使用文档
   */
  getLatestUseDoc: async () => {
    try {
      return await axios.get("/api/miniapp/get_latest_use_doc");
    } catch (error) {
      console.error("获取最新使用文档异常", error);
      throw error;
    }
  },

  /**
   * 获取所有使用文档
   * @returns {Promise<Object>} 返回所有使用文档
   */
  getAllUseDocs: async () => {
    try {
      return await axios.get("/api/miniapp/use_docs");
    } catch (error) {
      console.error("获取所有使用文档异常", error);
      throw error;
    }
  },

  /**
   * 创建使用文档
   * @param {Object} docData - 文档数据
   * @returns {Promise<Object>} 返回创建结果
   */
  createUseDoc: async (docData: { title: string; content: string }) => {
    try {
      return await axios.post("/api/miniapp/use_docs", docData, {
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.error("创建使用文档异常", error);
      throw error;
    }
  },

  /**
   * 更新指定文档
   * @param {number} docId - 文档ID
   * @param {Object} docData - 文档数据
   * @returns {Promise<Object>} 返回更新结果
   */
  updateUseDocById: async (docId: number, docData: { title: string; content: string }) => {
    try {
      return await axios.put(`/api/miniapp/use_docs/${docId}`, docData, {
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.error("更新指定文档异常", error);
      throw error;
    }
  },

  /**
   * 删除指定文档
   * @param {number} docId - 文档ID
   * @returns {Promise<Object>} 返回删除结果
   */
  deleteUseDoc: async (docId: number) => {
    try {
      return await axios.delete(`/api/miniapp/use_docs/${docId}`);
    } catch (error) {
      console.error("删除指定文档异常", error);
      throw error;
    }
  },

  /**
   * 更新使用文档
   * @param {Object} docData - 文档数据
   * @returns {Promise<Object>} 返回更新结果
   */
  updateUseDoc: async (docData: { content: string }) => {
    try {
      return await axios.put("/api/miniapp/use_doc", docData.content, {
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.error("更新使用文档异常", error);
      throw error;
    }
  },

  /**
   * 解绑识别码
   * @returns {Promise<Object>} 返回解绑结果
   */
  unbindRecognitionCode: async () => {
    try {
      return await axios.post("/api/miniapp/unbind_recognition_code", null, {
        params: {
          user_id: localStorage.getItem("userId"),
          access_token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("解绑识别码异常", error);
      throw error;
    }
  },

  /**
   * 获取所有教师信息
   * @returns {Promise<Object>} 返回所有教师信息
   */
  getAllTeachers: async () => {
    try {
      return await axios.get("/api/teacher/get_all_teachers", {
        params: {
          user_id: localStorage.getItem("userId"),
          token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("获取所有教师信息异常", error);
      throw error;
    }
  },

  /**
   * 根据关键词搜索教师
   * @param {string} keyword - 搜索关键词
   * @returns {Promise<Object>} 返回搜索结果
   */
  searchTeachers: async (keyword: string) => {
    try {
      return await axios.get("/api/teacher/search_teachers", {
        params: {
          keyword: keyword,
          user_id: localStorage.getItem("userId"),
          token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("搜索教师异常", error);
      throw error;
    }
  },

  /**
   * 添加教师信息
   * @param {Object} teacherData - 教师数据
   * @param {string} teacherData.folder_name - 院系名称
   * @param {string} teacherData.user_id - 教师工号
   * @param {string} teacherData.cn_name - 中文名称
   * @returns {Promise<Object>} 返回添加结果
   */
  addTeacher: async (teacherData: { folder_name: string; user_id: string; cn_name: string }) => {
    try {
      return await axios.post("/api/teacher/add_teacher", teacherData, {
        params: {
          user_id: localStorage.getItem("userId"),
          token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("添加教师信息异常", error);
      throw error;
    }
  },

  /**
   * 批量导入教师信息
   * @param {FormData} formData - 包含Excel文件的表单数据
   * @returns {Promise<Object>} 返回导入结果
   */
  importTeachers: async (formData: FormData) => {
    try {
      formData.append("user_id", localStorage.getItem("userId") || "");
      formData.append("token", localStorage.getItem("token") || "");

      return await axios.post("/api/teacher/import_teachers", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        },
        timeout: 600000
      });
    } catch (error) {
      console.error("批量导入教师信息异常", error);
      throw error;
    }
  },

  /**
   * 更新教师信息
   * @param {Object} teacherData - 教师数据
   * @param {number} teacherData.id - 教师ID
   * @param {string} teacherData.folder_name - 院系名称
   * @param {string} teacherData.user_id - 教师工号
   * @param {string} teacherData.cn_name - 中文名称
   * @returns {Promise<Object>} 返回更新结果
   */
  updateTeacher: async (teacherData: { id: number; folder_name: string; user_id: string; cn_name: string }) => {
    try {
      return await axios.put("/api/teacher/update_teacher", teacherData, {
        params: {
          user_id: localStorage.getItem("userId"),
          token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("更新教师信息异常", error);
      throw error;
    }
  },

  /**
   * 删除教师信息
   * @param {number} teacherId - 教师ID
   * @returns {Promise<Object>} 返回删除结果
   */
  deleteTeacher: async (teacherId: number) => {
    try {
      return await axios.delete("/api/teacher/delete_teacher", {
        params: {
          teacher_id: teacherId,
          user_id: localStorage.getItem("userId"),
          token: localStorage.getItem("token")
        }
      });
    } catch (error) {
      console.error("删除教师信息异常", error);
      throw error;
    }
  },

  /**
   * 获取所有校历
   * @returns {Promise<Object>} 返回所有校历数据
   */
  getAllSchoolCalendars: async () => {
    try {
      return await axios.get("/api/school-calendar/");
    } catch (error) {
      console.error("获取校历列表异常", error);
      throw error;
    }
  },

  /**
   * 获取指定校历
   * @param {string} title - 校历标题
   * @returns {Promise<Object>} 返回指定校历数据
   */
  getSchoolCalendarByTitle: async (title: string) => {
    try {
      return await axios.get(`/api/school-calendar/${title}`);
    } catch (error) {
      console.error("获取校历详情异常", error);
      throw error;
    }
  },

  /**
   * 预览校历
   * @param {string} title - 校历标题
   * @returns {Promise<Object>} 返回校历HTML内容
   */
  previewSchoolCalendar: async (title: string) => {
    try {
      return await axios.get(`/api/school-calendar/preview/${title}`);
    } catch (error) {
      console.error("预览校历异常", error);
      throw error;
    }
  },

  /**
   * 创建新校历
   * @param {Object} calendarData - 校历数据
   * @param {string} calendarData.school_title - 校历标题
   * @param {string} calendarData.calendar_content - 校历内容
   * @returns {Promise<Object>} 返回创建结果
   */
  createSchoolCalendar: async (calendarData: { school_title: string; calendar_content: string }) => {
    try {
      return await axios.post("/api/school-calendar/", calendarData);
    } catch (error) {
      console.error("创建校历异常", error);
      throw error;
    }
  },

  /**
   * 更新校历
   * @param {string} title - 校历标题
   * @param {Object} calendarData - 校历数据
   * @param {string} calendarData.calendar_content - 校历内容
   * @returns {Promise<Object>} 返回更新结果
   */
  updateSchoolCalendar: async (title: string, calendarData: { calendar_content: string }) => {
    try {
      return await axios.put(`/api/school-calendar/${title}`, calendarData);
    } catch (error) {
      console.error("更新校历异常", error);
      throw error;
    }
  },

  /**
   * 删除校历
   * @param {string} title - 校历标题
   * @returns {Promise<Object>} 返回删除结果
   */
  deleteSchoolCalendar: async (title: string) => {
    try {
      return await axios.delete(`/api/school-calendar/${title}`);
    } catch (error) {
      console.error("删除校历异常", error);
      throw error;
    }
  },

  /**
   * 从远程同步校历
   * @param {string} authorizationToken - 授权令牌
   * @returns {Promise<Object>} 返回同步结果
   */
  syncSchoolCalendarsFromRemote: async (authorizationToken: string) => {
    try {
      return await axios.post("/api/school-calendar/sync_from_remote", null, {
        params: { authorization_token: authorizationToken }
      });
    } catch (error) {
      console.error("同步校历异常", error);
      throw error;
    }
  },

  /**
   * 获取about.md模板内容
   * @returns {Promise<Object>} 返回模板内容
   */
  getAboutTemplate: async () => {
    try {
      return await axios.get("/api/miniapp/get_about_template");
    } catch (error) {
      console.error("获取模板内容异常", error);
      throw error;
    }
  },

  /**
   * 更新about.md模板内容
   * @param {string} content - 模板内容
   * @returns {Promise<Object>} 返回更新结果
   */
  updateAboutTemplate: async (content: string) => {
    try {
      return await axios.post("/api/miniapp/update_about_template", { content });
    } catch (error) {
      console.error("更新模板内容异常", error);
      throw error;
    }
  },

  /**
   * 恢复about.md模板备份
   * @returns {Promise<Object>} 返回恢复结果
   */
  restoreAboutTemplate: async () => {
    try {
      return await axios.post("/api/miniapp/restore_about_template");
    } catch (error) {
      console.error("恢复模板备份异常", error);
      throw error;
    }
  },

  /**
   * 上传打赏Excel文件
   * @param {File} file - Excel文件
   * @returns {Promise<Object>} 返回上传结果
   */
  uploadDonationExcel: async (file: File) => {
    try {
      const formData = new FormData();
      formData.append("file", file);

      return await axios.post("/api/miniapp/upload_donation_excel", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });
    } catch (error) {
      console.error("上传打赏Excel文件异常", error);
      throw error;
    }
  },

  /**
   * 上传校园地图图片
   * @param {string} imageType - 图片类型: 'gzxq' 或 'jmxq'
   * @param {File} file - 上传的图片文件
   * @param {Function} onUploadProgress - 上传进度回调函数
   * @returns {Promise<Object>} 返回上传结果
   */
  uploadCampusMapImage: async (imageType: string, file: File, onUploadProgress?: (progressEvent: any) => void) => {
    try {
      const formData = new FormData();
      formData.append("image_type", imageType);
      formData.append("file", file);

      return await axios.post("/api/school-calendar/upload_image", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        },
        onUploadProgress: onUploadProgress
      });
    } catch (error) {
      console.error("上传校园地图图片异常", error);
      throw error;
    }
  },

  /**
   * 获取带学年学期字段的用户列表
   * @returns {Promise<Object[]>} 用户列表
   */
  getUserSemesters: async () => {
    try {
      return await axios.get("/api/miniapp/semesters");
    } catch (error) {
      console.error("获取用户学期列表异常", error);
      throw error;
    }
  },

  /**
   * 批量更新用户的学年学期数据
   * @param {Object} payload - 包含 usernames, amount, current_year, current_term
   * @returns {Promise<Object>} 更新结果
   */
  updateUserSemesters: async (payload: {
    usernames: string;
    amount: number;
    current_year: number;
    current_term: number;
  }) => {
    try {
      return await axios.post("/api/miniapp/semesters/update", payload);
    } catch (error) {
      console.error("更新用户学年学期异常", error);
      throw error;
    }
  }
};
